package com.example.client;


import com.example.message.ChatRequestMessage;
import com.example.message.GroupChatRequestMessage;
import com.example.message.GroupCreateRequestMessage;
import com.example.message.GroupJoinRequestMessage;
import com.example.message.GroupMembersRequestMessage;
import com.example.message.GroupQuitRequestMessage;
import com.example.message.LoginRequestMessage;
import com.example.message.LoginResponseMessage;
import com.example.message.PingMessage;
import com.example.protocol.MessageCodecSharable;
import com.example.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.NetUtil;
import io.netty.util.internal.PlatformDependent;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        boolean windows = PlatformDependent.isWindows();
        log.debug("windows:{}", windows);
        log.info("test:{}", NetUtil.LOCALHOST);
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        // 这个知识点需要认证学一下。。。
        CountDownLatch WAITING_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        try {
            Bootstrap bootstrap = new Bootstrap();
//            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000); // 设置超时异常
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    //ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);

                    // 空闲事件检测
                    ch.pipeline().addLast(new IdleStateHandler(0, 10, 0));
                    // 关注上面产生的事件
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            // 用来触发特殊事件
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了读空闲事件
                            if (event.state() == IdleState.WRITER_IDLE) {
                                log.debug("3秒没有写数据了，自动发一个心跳包。");
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });

                    ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {
                        // 连接建立触发active
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // 新线程接受用户在控制台的输入
                            new Thread(() -> {
                                System.out.println("请输入用户名：");
                                Scanner scanner = new Scanner(System.in);
                                String username = scanner.nextLine();
                                System.out.println("请输入密码：");
                                String password = scanner.nextLine();
                                LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password);
                                // 发消息
                                ctx.writeAndFlush(loginRequestMessage);
                                // hang在这个位置
                                try {
                                    WAITING_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                // 失败 就退出线程 关闭channel
                                if (!atomicBoolean.get()) {
                                    Channel channel = ctx.channel();
                                    channel.close();
                                    return;
                                }
                                // 登录成功进入菜单选择自己需要的功能
                                while (true) {
                                    System.out.println("======================");
                                    // menu
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3,...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("======================");
                                    // 用户输入  hang在这个位置
                                    String command = scanner.nextLine();
                                    // 解析命令
                                    String[] s = command.split(" ");
                                    switch (s[0]) {
                                        case "send":
                                            ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
                                            break;
                                        case "gcreate":
                                            List<String> strings = Arrays.asList(s[2].split(","));
                                            strings.add(username); // 将自己拉进去
                                            HashSet<String> strings1 = new HashSet<>(strings);
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], strings1));
                                            break;
                                        case "gmembers":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username, s[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username, s[1]));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }

                                }
                            }, "system in").start();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.info("msg:{}", msg);
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage message = (LoginResponseMessage) msg;
                                // 将 登录结果 赋值给这个变量
                                atomicBoolean.set(message.isSuccess());
                                // 唤醒另外一个线程
                                WAITING_FOR_LOGIN.countDown();
                            }
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
